<?php

namespace app\api\controller;

use app\controller\api\BaseController;
use app\logic\api\LoginLogic;
use common\validate\common\LoginValidate;
use support\Container;
use support\Request;

/**
 * 客户端登录
 * Class LoginController
 * @package app\api\controller
 * @author ycr <Email: yuncran@126.com>
 */
class SiteController extends BaseController
{

    /**
     * 签名验证 -白名单
     * @var array
     */
    protected $signOptional = ['/api/login', '/api/register', '/api/captcha'];

    /**
     * 权限验证 -白名单
     * @var array
     */
    protected $authOptional = ['*'];

    /**
     * @Inject
     * @var LoginLogic  logic
     */
    protected $logic;

    public function __construct()
    {
        $this->logic = Container::get(LoginLogic::class);
    }

    /**
     * 用户登录
     * @author ycr <Email: yuncran@126.com>
     */
    public function login(Request $request)
    {
        $param = $request->post();
        try {
            $validate = new LoginValidate();
            if (!$validate->scene('login')->check($param)) {
                return app('json')->fail($validate->getError());
            }
            $login = $this->logic->siteLogin($param, $request);
        } catch (\Throwable $exception) {
            return app('json')->fail($exception->getMessage());
        }
        return app('json')->success('登录成功', $login);
    }


    /** 注册服务信息 */
    public function register(Request $request)
    {
        $param = $request->post();
        $validate = new LoginValidate();
        if (!$validate->scene('register')->check($param)) {
            return app('json')->fail($validate->getError());
        }
        $register = $this->logic->register($param, $request);
        return app('json')->success('注册成功', $register);
    }

    /**
     * 重置令牌
     * @return mixed
     * @author ycr <Email: yuncran@126.com>
     */
    public function refreshToken()
    {
        try {
            $token = Yii()->access_token->refreshToken();
        } catch (\Throwable $exception) {
            return app('json')->fail($exception->getMessage());
        }
        return app('json')->success($token);
    }


    /**
     * 验证码
     * @return mixed
     * @author ycr <Email: yuncran@126.com>
     */
    public function captcha()
    {
        return $this->logic->captcha();
    }

    /**
     * 退出登录
     * @author ycr <Email: yuncran@126.com>
     */
    public function logout()
    {
        return Yii()->access_token->logout();
    }
}